#include "httpproc.h"
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QHttpMultiPart>

#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonValue>
#include <QFile>

CHttpProc::CHttpProc(QObject *parent):QObject(parent)
{
    m_pHttpManager = new QNetworkAccessManager(this);
    m_pHttpMultiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    connect(m_pHttpManager, SIGNAL(finished(QNetworkReply*)),
              this, SLOT(replyFinished(QNetworkReply*)));
}

CHttpProc::~CHttpProc()
{

}

void CHttpProc::getTextFormData(QString strFieldName, QString strFieldValue)
{
    QString strFormdata = QString("form-data;name=\"%1\"").arg(strFieldName);
    QHttpPart textPart;
    textPart.setHeader(QNetworkRequest::ContentDispositionHeader, strFormdata);
    textPart.setBody(strFieldValue.toStdString().c_str());
    m_pHttpMultiPart->append(textPart);
    return;
}

void CHttpProc::getBMPFormData(QString strFieldName, QString strFileName, QString strNewFileName)
{
    QFile* pFile = new QFile(strFileName);
    if(pFile->open(QIODevice::ReadOnly))
    {
        QString strFormdata = QString("form-data;name=\"%1\";filename=\"%2\"").arg(strFieldName).arg(strNewFileName);
        QHttpPart imagePart;
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-bmp"));
        imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, strFormdata);
        imagePart.setBodyDevice(pFile);
        m_pHttpMultiPart->append(imagePart);
        pFile->setParent(m_pHttpMultiPart);
    }
    else
    {
        qDebug("open phote file failed:%s.\n", pFile->errorString().toStdString().c_str());
    }

    return;
}

void CHttpProc::postLocalData(QStringList list)
{ 
    if(!list.isEmpty())
    {//体检表单行数据上传      
        QNetworkRequest req;

//        QString strUrl = CCommon::Instance()->GetIniFilePtr()->GetUrlLocal();
//        req.setUrl(strUrl);

//        m_pHttpMultiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
//        m_strCheckDate = list.at(0);
//        m_strId = list.at(1);
//        getTextFormData("healthCheck.checkDate", list.at(0));
//        getTextFormData("healthCheck.identitycardNum", list.at(1));
//        getTextFormData("healthCheck.height", list.at(2));
//        getTextFormData("healthCheck.weight", list.at(3));

//        getTextFormData("healthCheck.fatPercentage", list.at(4));
//        getTextFormData("healthCheck.bmr", list.at(5));
//        getTextFormData("healthCheck.ppmv", list.at(6));
//        getTextFormData("healthCheck.skeletalMuscle", list.at(7));

//        getTextFormData("healthCheck.bmc", list.at(8));
//        getTextFormData("healthCheck.extracellularFluid", list.at(9));
//        getTextFormData("healthCheck.bodyAge", list.at(10));
//        getTextFormData("healthCheck.syntheticalMark", list.at(11));

//        getTextFormData("healthCheck.animalHeat", list.at(12));
//        getTextFormData("healthCheck.systolicPressure", list.at(13));
//        getTextFormData("healthCheck.diastolicPressure", list.at(14));
//        getTextFormData("healthCheck.pulseRate", list.at(15));
//        getTextFormData("healthCheck.bloodSugar", list.at(16));
//        getTextFormData("healthCheck.uricAcid", list.at(17));
//        getTextFormData("healthCheck.cholesterin", list.at(18));

//        QString strTimeStamp = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
//        getTextFormData("timestamp", strTimeStamp);

//        QString strSrcMd5 = strTimeStamp+"88989982";
//        QString strMd5 = QCryptographicHash::hash(strSrcMd5.toLatin1(), QCryptographicHash::Md5).toHex();
//        getTextFormData("key", strMd5);

//        qInfo("[---Post Local Data---] url: %s\n", strUrl.toStdString().c_str());
//        m_pHttpManager->post(req, m_pHttpMultiPart);
    }
}

void CHttpProc::postPulseWaveData(QString strSYS, QString strDIA, QString strPUL, void *pContext)
{
//    m_pFriendPulse = pContext;
//    QString strTimeStamp = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
//    QString strSrcMd5 = strTimeStamp+"88989982";
//    QString strMd5 = QCryptographicHash::hash(strSrcMd5.toLatin1(), QCryptographicHash::Md5).toHex();
//    QString strUrl = CCommon::Instance()->GetIniFilePtr()->GetUrlPluseWave();
//    QString strIdCardNo = CCommon::Instance()->GetIdCardNo();
//    QString strOrgID = CCommon::Instance()->GetIniFilePtr()->GetOrgCfg().strOrgId;

//    strUrl += QString("identitycardNum=%1").arg(strIdCardNo);
//    strUrl += QString("&hospitalInfoID=%1").arg(strOrgID);
//    strUrl += QString("&systolicPressure=%1").arg(strSYS);
//    strUrl += QString("&diastolicPressure=%1").arg(strDIA);
//    strUrl += QString("&pulseRate=%1").arg(strPUL);
//    strUrl += QString("&timestamp=%1").arg(strTimeStamp);
//    strUrl += QString("&key=%1").arg(strMd5);

//    qDebug("[---CPulsewaveDev---] start post: %s\n", strUrl.toStdString().c_str());
//    m_pHttpManager->get(QNetworkRequest(QUrl(strUrl)));
}

void CHttpProc::replyFinished(QNetworkReply *reply)
{    
//    QString strUrlResponse = reply->url().toString();
//    if(strUrlResponse.contains(CCommon::Instance()->GetIniFilePtr()->GetUrlPluseWave()))
//    {
//      //  resPonsePulseWave(reply);
//    }
}

void CHttpProc::resPonseLocalData(QNetworkReply *reply)
{
//    bool result = false;
//    if(reply->error() == reply->NoError)
//    {
//        QByteArray jsonData = reply->readAll();
//        QJsonParseError json_error;
//        QJsonDocument json_doc = QJsonDocument::fromJson(jsonData, &json_error);
//        if(QJsonParseError::NoError == json_error.error)
//        {
//            QJsonObject objRes = json_doc.object();
//            result = objRes["success"].toBool();
//            if(!result)
//            {
//                int nErr = objRes["error"].toInt();
//                QString strReson = objRes["reason"].toString();

//                qDebug("[---LocalData---]post data to web error: %s.\n",strReson.toStdString().c_str());
//                if(-1 == nErr)
//                {//身份证档案未建立
//                    CCommon::Instance()->GetCommitPtr()->ShowMsg(tr("Post check data failed,id file has not been established."));
//                    emit sigPostIdInfo(m_strId);
//                    return;
//                }
//            }
//            else
//            {//提交后台成功，删除本地数据
//                CCommon::Instance()->GetCommitPtr()->ShowMsg(tr("Post check data success."));

//                qDebug("[---LocalData---] post idcard data success.\n");
//                QString strSql = "delete from tab_health where time=";
//                strSql += QString("'%1' and ").arg(m_strCheckDate);
//                strSql += QString("identitycardNum='%1'").arg(m_strId);

//                bool bRet = CCommon::Instance()->GetSqlite3Ptr()->Execute(strSql);
//                if(!bRet)
//                {
//                    qWarning("[---LocalData---] delete sql: %s failed.", strSql.toStdString().c_str());
//                }
//                else
//                {

//                }
//            }
//          }
//        else
//        {
//            qDebug("[---LocalData---] recv web respons data error: %s.data:%s\n", json_error.errorString().toStdString().c_str(),jsonData.constData());
//        }
//    }
//    else
//    {
//        qDebug("[---LocalData---]post data to web reply error: %s.\n", reply->errorString().toStdString().c_str());
//    }

//    if(!result)
//    {
//        QString str = tr("please check net, post failed!") + "\n";
//        CCommon::Instance()->GetCommitPtr()->ShowMsg(str);
//    }
}

void CHttpProc::resPonsePulseWave(QNetworkReply *reply)
{
    bool result = false;   
    if(reply->error() == reply->NoError)
    {
        QByteArray jsonData = reply->readAll();
        QJsonParseError json_error;
        QJsonDocument json_doc = QJsonDocument::fromJson(jsonData, &json_error);
        if(QJsonParseError::NoError == json_error.error)
        {
            QJsonObject objRes = json_doc.object();
            result = objRes["success"].toBool();
            if(!result)
            {
                qDebug("[---CPulsewaveDev---]post data to web error: %s.\n",objRes["reason"].toString().toStdString().c_str());
            }
            else
            {
                qDebug("[---CPulsewaveDev---] post pulwave data success.\n");
            }
          }
        else
        {
            qDebug("[---CPulsewaveDev---] recv web respons data error: %s.data:%s\n", json_error.errorString().toStdString().c_str(),jsonData.constData());
        }
    }
    else
    {
        qDebug("[---CPulsewaveDev---]post data to web reply error: %s.\n", reply->errorString().toStdString().c_str());
    }
}

void CHttpProc::slotPostIdInfo(QString strIdCard)
{//上传本地身份证数据
    QString strSql = "select * from tab_idcard where identitycardNum='";
    strSql += QString("%1'").arg(strIdCard);

//    QString str = tr("start post id: ")+strIdCard + tr("...\n");
//    QStringList list = CCommon::Instance()->GetSqlite3Ptr()->GetFirstIdcard(strSql, 6);
//    if(list.size() != 0)
//    {
//       postIdCardData(list);
//    }
//    else
//    {
//        str += tr("This id card not found.")+"\n";
//    }
//    CCommon::Instance()->GetCommitPtr()->ShowMsg(str);
}
